<?php

namespace backend\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\data\Pagination;
use yii\db\ActiveRecord;
use yii\db\BaseActiveRecord;
use yii\db\Query;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "article".
 *
 * @property integer $id
 * @property string $name
 * @property integer $article_category_id
 * @property string $intro
 * @property integer $status
 * @property integer $sort
 * @property integer $inputtime
 */
class Article extends ActiveRecord
{
    public static $statusValue = [0=>'是',1=>'否',-1=>'已经删除'];

    public static $pagesize=7;

    /** @var  $contentObj BaseActiveRecord */
    public $contentObj;

    public function behaviors()
    {
        return [
            [
                'class'=>TimestampBehavior::className(),
                'createdAtAttribute'=>['inputtime'],
                'updatedAtAttribute'=>['inputtime'],
//                'value'=>time(),
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'article';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name','article_category_id', 'status', 'inputtime'], 'required'],
            [['article_category_id', 'status', 'sort', 'inputtime'], 'integer'],
            [['intro'], 'string'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'article_category_id' => '文章分类',
            'intro' => '简介',
            'status' => '是否上架',
            'sort' => '排序',
            'inputtime' => '录入时间',
        ];
    }

    /*
     * 的到文章的所有的分类
     */
    public function getArticleCategory(){
      return   $this->hasOne(ArticleCategory::className(),['id'=>'article_category_id']);
    }

    public static function getArticleCates(){
        //获取所有的文章分类的数据
        $categorys = ArticleCategory::find()->asArray()->all();
        //得到按要求组成的数组
        $cates = ArrayHelper::map($categorys,'id','name');

        return $cates;
    }
    /*
     * 获取文章的类容属性
     */
    public function getContent()
    {
        return $this->hasOne(Article_detail::className(),['article_id'=>'id']);
    }

    /**
     * @return bool
     */
    public function saveData(){
        $this->inputtime = time();
        if($this->validate() && $this->contentObj->validate()){
            //验证数据成功后保存数据
            $this->save();
            $this->contentObj->article_id = $this->id;
            //保存文章的内容
            return $this->contentObj->save();
        }
        return false;
    }



}
